package mysql

import (
	"month_zg5/book_srv/common/global"
	"month_zg5/book_srv/models"
	book_rpc "month_zg5/book_srv/proto"
)

func GetBookAll() ([]*models.Book, error) {
	var book []*models.Book
	return book, global.DB.Order("readings DESC").Find(&book).Error
}

// 浏览量倒叙排列
func GetBookDescByReadings() ([]*models.Book, error) {
	var book []*models.Book
	err := global.DB.Order("readings ASC").Limit(10).Find(&book).Error
	return book, err
}

// 添加到书架
func CreateBookShelf(bookshelf *models.BookShelf) error {
	return global.DB.Create(&bookshelf).Error
}

// 无限极分类
func GetBookType(pid int) ([]*book_rpc.BookTypeInfo, error) {
	var (
		bookTypes []*models.BookType
		list      []*book_rpc.BookTypeInfo
	)
	err := global.DB.Preload("BookType").Where("pid=?", pid).Find(&bookTypes).Error
	if err != nil {
		return nil, err
	}
	for _, v := range bookTypes {
		var data = &book_rpc.BookTypeInfo{
			Id:    uint32(v.Id),
			Pid:   uint32(v.Pid),
			Title: v.Title,
		}
		list = append(list, data)
	}
	return list, nil
}

// 文章详情
func GetBookDetail(book_id uint) (*book_rpc.BookInfo, error) {
	var (
		bookcommons []*book_rpc.CommonInfo
		book        = new(models.Book)
	)
	err := global.DB.Preload("Common").Preload("Common.Common", "book_id = ?", book_id).First(&book).Error
	if err != nil {
		return nil, err
	}
	for _, v := range book.Common {
		var bookinfo = &book_rpc.CommonInfo{
			Id:      uint32(v.ID),
			UserId:  uint32(v.UserId),
			BookId:  uint32(v.BookId),
			Content: v.Content,
			Pid:     uint32(v.Pid),
		}
		bookcommons = append(bookcommons, bookinfo)
	}
	bookInfo := &book_rpc.BookInfo{
		Title:            book.Title,
		BookType:         int32(book.BookType),
		Author:           book.Author,
		Content:          book.Content,
		NumberOfComments: int32(book.NumberOfComments),
		Readings:         int32(book.Readings),
		CommonInfo:       bookcommons,
	}
	return bookInfo, nil
}

// 添加评论
func AddComment(comment *models.Common) error {
	return global.DB.Create(&comment).Error
}
func SaveBook(book_id uint) (*models.Book, error) {
	var book *models.Book
	err := global.DB.Where("id = ?", book_id).First(&book).Error
	if err != nil {
		return nil, err
	}
	book.NumberOfComments += 1
	return book, global.DB.Save(&book).Error
}
